﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography;
using System.Net.Sockets;
using System.IO;

namespace revoStore.Users
{
    class UserServer
    {
        WebClient webClient = new WebClient();

        public static bool LogIn(string user, string pass)
        {
            string md5 = MD5Hash(pass);

            TcpClient tcpClient = new TcpClient("http://revostore.zapto.org", 80);
            try
            {
                Stream stream = tcpClient.GetStream();
                StreamReader streamReader = new StreamReader(stream);
                StreamWriter streamWriter = new StreamWriter(stream);
                streamWriter.AutoFlush = true;
                string value = (user + ':' + md5);
                streamWriter.WriteLine(value);
                string a = streamReader.ReadLine();
                if (a == "true")
                {
                    return true;
                }
                else if (a == "false")
                {
                    return false;
                }
                else
                {
                    throw new WebException("revoStore is having some problems. Please retry later.");
                }
            }
            finally
            {
                tcpClient.Close();
            }
        }

        public static string MD5Hash(string text)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            //compute hash from the bytes of text
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));

            //get hash result after compute it
            byte[] result = md5.Hash;

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                //change it into 2 hexadecimal digits
                //for each byte
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
    }
}
